﻿#ifndef NDC_CLIENT_H
#define NDC_CLIENT_H

#include <QObject>

#include "modbus.h"

#include <QModbusDataUnit>
#include <QModbusTcpClient>
#include <QUrl>
#include <QTime>
#include <QCoreApplication>

class QModbusClient;
class QModbusReply;

class NDC_Client : public QObject
{
    Q_OBJECT
public:

    ~NDC_Client();

    explicit NDC_Client(QObject *parent = 0);

    bool connectToHost(std::string , int port);

    bool disconnect();

    bool check_Modbus_Available();

    void setModbusPtr(modbus* modbus);

    bool read_AGV_State();

    //uint16_t* read_AGV_data();
    //uint16_t* read_product_qrlandmark_data();

    bool write_ADV_data_64(int data64);
    bool write_ADV_data_65(int data65);
    bool write_ADV_data_66(int data66);
    bool write_ADV_data_67(int data67);

    bool write_AGV_data_68(int data68);

    bool write_AGV_data_69(int data69);

    //bool write_AGV_data(int index, int data);



    bool Func_get_station_id(QString& value);
    bool Func_allow_take_workpiece_from_CNC(int& value);
    bool Func_allow_put_raw_workpiece_to_CNC(int& value);
    bool Func_allow_take_raw_workpiece_from_lifter(int& value);
    bool Func_allow_put_workpiece_to_lifter(int& value);
    bool Func_AGV_arrive_station_number(int& number);
    bool Func_get_AGV_state(int& value);

    bool Func_finished_putting_raw_workpiece_to_CNC(int& value);
    bool Func_finished_taking_workpiece_from_CNC(int& value);
    bool Func_allow_lifter_movement(int& value);

    //bool write_taking_state_to_NDC(bool state);
    //bool write_putting_state_to_NDC(bool state);
    //bool write_allow_lifter_movement(bool state);
    bool write_DM_code_to_NDC(std::string message);

    bool write_data(int start,int number,int* data);
    void sleep_ms(int msecond);

signals:

public slots:
        void readReady();

private:
    QModbusDataUnit readRequest() const;
    QModbusDataUnit writeRequest(int start,int number) const;

private:
    modbus* modbus_ = nullptr;

    int station_number;
    int allow_put_raw_workpiece_to_CNC; // 以AGV为基准，下料
    int allow_take_workpiece_from_CNC;  // 以AGV为基准，上料
    int allow_take_raw_workpiece_from_lifter;
    int allow_put_workpiece_to_lifter;
    int AGV_State;

    //
    bool finished_taking_workpiece_from_CNC;    // 以AGV为基准，上料
    bool finished_putting_raw_workpiece_to_CNC; // 以AGV为基准，下料
    bool allow_lifter_movement;

    //uint16_t read_holding_regs[6];
    uint16_t read_holding_regs_product_qrlandark[17];

    std::string m_host;
    int m_port;


    //
    QModbusReply *lastRequest = nullptr;
    QModbusClient *modbusDevice = nullptr;

    bool reply_state = false;
};

#endif // NDC_CLIENT_H
